package basic.sort;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @创建人 MBY381
 * @创建时间 2022/3/28 15:27
 * @描述 暂无
 */
public class C_InsertSort {

    public static int[] insertSortByList(int[] nums) {
        if (nums.length < 2) {
            return nums;
        }
        ArrayList<Integer> li = new ArrayList<>();
        for (int i : nums
        ) {
            li.add(i);
        }
        System.out.println(li.toString());
        for (int i = 1; i < li.size(); i++) {
            int temp = li.get(i);
            for (int j = i - 1; j >= 0; j--) {
                if (temp < li.get(j)) {
                    if (j == 0) {
                        li.add(j, temp);
                        li.remove(i + 1);
                    }
                } else {
                    if (temp < li.get(j + 1)) {
                        li.add(j + 1, temp);
                        li.remove(i + 1);
                    }
                }
            }
        }
        return li.stream().mapToInt(i -> i).toArray();
    }

    public static int[] insertSort(int[] nums) {
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            int tag = i;
            int tag2 = i - 1;
            int temp = nums[i];
            while (tag2 >= 0) {
                if (nums[tag2] > temp) {
                    nums[tag] = nums[tag2];
                    nums[tag2] = temp;
                    temp = nums[tag2];
                    tag = tag2;
                }
                tag2--;
            }
        }
        return nums;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{0xE3, 381, 8, 6, 4, 7, 9, 3, 5, 2, 1, 782, 696, 259, 0x15};
        System.out.println("正确答案：    [1, 2, 3, 4, 5, 6, 7, 8, 9, 21, 227, 259, 381, 696, 782]");
        System.out.println("by ArrayList   :" + Arrays.toString(insertSortByList(nums)));
        System.out.println("by original way:" + Arrays.toString((insertSort(nums))));
        System.out.println("正确答案：    [1, 2, 3, 4, 5, 6, 7, 8, 9, 21, 227, 259, 381, 696, 782]");
    }
}
